<script setup lang="ts">

import OpeningRemarks from '@/views/agent/chat/components/OpeningRemarks.vue'
import UploadFile from '@/views/agent/chat/components/UploadFile.vue'
import StepLoading from '@/views/agent/chat/components/StepLoading.vue'
import { cloneDeep, orderBy } from 'lodash'
import { computed, nextTick, ref } from 'vue'
import { ResumeEvaluationProcessLoading, JDAgent, resumeAgent, CONTENT_REGEXP } from '@/views/agent/chat/components/data'
import applicationApi from '@/api/application'
import * as echarts from 'echarts';

const props = withDefaults(
  defineProps<{
    appId?: any
    chatId?: string
    applicationDetails: any
  }>(),
  {
  }
)
const tip = 'AI简历打分系统通过分析求职者的经验、技能、教育背景以及职位匹配度，提供客观评价'
const step = ref(0)
const topTips = ref(tip)
const loading = ref(false)

const file = ref({
  jd: [],
  resume: []
})

const chatInfo: any = ref({
  jdChatId: '',
  jdContent: [],
  resumeChatId: '',
  resumeContent: [],
  integratedContent: [],
})

const setDocumentList = async (val: any, chatId?: string) => {
  try {
    file.value.jd = val;
    loading.value = true
    chatInfo.value.jdChatId = chatId || '';
    if (!chatInfo.value.jdChatId) {
      const chatData = await applicationApi.getChatOtherOpen(JDAgent.appId, JDAgent.apiKey)
      chatInfo.value.jdChatId = chatData.data
    }
  } finally {
    loading.value = false
  }
}

const setDocumentListOne = async (val: any, id: string) => {
  try {
    file.value.resume = val;
    loading.value = true
    chatInfo.value.resumeChatId = id || '';
    if (!chatInfo.value.resumeChatId) {
      const chatData = await applicationApi.getChatOtherOpen(resumeAgent.appId, resumeAgent.apiKey)
      chatInfo.value.resumeChatId = chatData.data
    }
  } finally {
    loading.value = false
  }

}

const hasSubmit = computed(() => {
  return file.value.jd.length > 0 && file.value.resume.length > 0 && !loading.value
})
function onBack () {
  step.value = 0;
}
async function onSubmit () {
 loading.value = true
 step.value = 1;

 applicationApi.postChatMessageNew(chatInfo.value.jdChatId, { document_list: file.value.jd, stream: false, message: '请帮我总结JD核心。用于筛选简历', apiKey:  JDAgent.apiKey }).then((res) => {
   chatInfo.value.jdContent = JSON.parse(cloneDeep(res.data.content.replaceAll(CONTENT_REGEXP, '')))
   applicationApi.postChatMessageNew(chatInfo.value.resumeChatId, { document_list: file.value.resume, stream: false, message: res.data.content, apiKey:  resumeAgent.apiKey }).then((res) => {
     let resumeContent = JSON.parse(cloneDeep(res.data.content.replaceAll(CONTENT_REGEXP, '')))
     // 计算平均值
     resumeContent = resumeContent?.candidates.map((v: any) => {
       const total = v.scores.reduce((total: number, scoreObj: any) => {
         return total + scoreObj.score;
       }, 0)
       return {
         ...v,
         total_score: total / 5
       }
     })
     chatInfo.value.resumeContent = orderBy(resumeContent, 'total_score', 'desc')
     chatInfo.value.integratedContent = chatInfo.value.resumeContent.map((v: any) => {
       return {
         name: v.name,
         total_score: v.total_score,
         skills: v.scores[0].score,
         work: v.scores[1].score,
         education: v.scores[2].score,
         softSkills: v.scores[3].score,
         anomaly: v.scores[4].score,
       }
     })
     nextTick(() => {
       // 300 毫秒能渲染出来，测试异步是否能加载出来。
       setTimeout(() => {
         echartsRender(chatInfo.value.resumeContent)
       }, 300)
     })
     loading.value = false;
   })
 })
}

function echartsRender (val: any) {
  val.forEach((v: any, index: number) => {
    const chartDom = document.getElementById('radar-chart-' + index);
    const myChart = echarts.init(chartDom);
    const option = {
      grid: {
        left: '20%',
        right: '20%'
      },
      radar: {
        indicator: v.scores.map((skill: any) => ({ name: skill.category, max: 100 })),
        lineStyle: {
          width: 2, // 增加线条宽度
          type: 'solid' // 确保线条类型为实线
        }
      },
      series: [{
        type: 'radar',
        data: [
          {
            value: v.scores.map((skill: any) => skill.score),
            name: '候选人评分',
            lineStyle: {
              width: 2, // 增加线条宽度
              type: 'solid' // 确保线条类型为实线
            }
          }
        ]
      }]
    };
    myChart.setOption(option);
  })
}
</script>

<template>
  <OpeningRemarks class="mb-12" :title="props.applicationDetails.name" :description="props.applicationDetails.desc" :avatar="props.applicationDetails.avatar" />
  <el-card class="mt-12 mb-12" shadow="never" v-if="step !== 1">
    <div class="ai-start">
      <div class="ai-start-tips">
        <el-icon @click="onBack" v-if="step === 1"><ArrowLeftBold /></el-icon>
        <div class="ai-start-tips-ellipsis">
          {{ topTips }}
        </div>
      </div>
      <el-button type="primary" size="small" @click="onSubmit" :disabled="!hasSubmit">开始评价</el-button>
    </div>
  </el-card>
  <el-row :gutter="10" v-if="step === 0">
    <el-col :span="12">
      <UploadFile v-loading="loading" :app-id="JDAgent.appId" :api-key="JDAgent.apiKey" @update="setDocumentList" :max-files="1" name="JD" tip="支持格式：pdf、doc、docx格式文件" accept=".pdf,.docx,.doc" />
    </el-col>
    <el-col :span="12">
      <UploadFile :app-id="resumeAgent.appId" :api-key="resumeAgent.apiKey" @update="setDocumentListOne" :max-files="10" name="简历" tip="支持格式：pdf、doc、docx格式文件，<br/>一次至多上传10份简历" accept=".pdf,.docx,.doc" />
    </el-col>
  </el-row>
  <StepLoading v-if="step === 1" :data="ResumeEvaluationProcessLoading" :loading="loading" :applicationDetails="props.applicationDetails">
    <el-card>
      <div class="card-title">1、JD核心要求分析</div>
      <el-table :data="chatInfo.jdContent" border size="small">
        <el-table-column label="评估维度" prop="name" width="120"></el-table-column>
        <el-table-column label="具体要求" prop="value"></el-table-column>
      </el-table>
    </el-card>
    <el-card class="mb-12">
      <div class="card-title mb-8">2、候选人综合对比</div>
<!--      <div class="card-description">综合评价描述综合评价描述综合评价描述综合评价描述综合评价描述综合评价描述综合评价描述综合评价描述</div>-->
      <el-table :data="chatInfo.integratedContent" border size="small">
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="技能匹配度" prop="skills"></el-table-column>
        <el-table-column label="工作经验" prop="work"></el-table-column>
        <el-table-column label="教育背景" prop="education"></el-table-column>
        <el-table-column label="软技能" prop="softSkills"></el-table-column>
        <el-table-column label="职业发展连贯性" prop="anomaly"></el-table-column>
        <el-table-column label="综合评分" prop="total_score"></el-table-column>
      </el-table>
    </el-card>
    <el-card class="mb-12">
      <div class="card-title mb-8">3、候选人详细评价</div>
      <el-row v-for="(item, index) in chatInfo.resumeContent" :key="index" class="candidate-card">
        <el-col :span="12" class="candidate-card-left">
          <el-row class="candidate-card-left-name">
            <el-col :span="12">
              <div class="name ellipsis" style="font-weight: 600;font-size: 32px;line-height: 38px; max-width: 100px">
                <el-tooltip :content="item.name" v-if="item.name.length > 3">
                  {{ item.name }}
                </el-tooltip>
                <span v-else>{{ item.name }}</span>
              </div>
              <div style="font-weight: 400;font-size: 14px;color: rgba(0,0,0,0.4);line-height: 17px;margin-top: 10px;">面试者</div>
            </el-col>
            <el-col :span="12">
              <div class="name" style="font-weight: 600;font-size: 32px;color: #3767DD;line-height: 38px;">{{ item.total_score }}分</div>
              <div style="font-weight: 400;font-size: 14px;color: rgba(0,0,0,0.4);line-height: 17px;margin-top: 10px;">综合评分</div>
            </el-col>
            <div class="line"></div>
          </el-row>
          <el-row class="candidate-card-left-reason">
           <div class="candidate-card-left-reason-title">
             综合评价
           </div>
            <div class="candidate-card-left-reason-content">
              <el-tooltip :content="item.recommendation_reason">
                {{ item.recommendation_reason }}
              </el-tooltip>

            </div>
          </el-row>
        </el-col>
        <el-col :span="11" :offset="1" class="candidate-card-right">
          <div class="radar-chart">
            <div :id="'radar-chart-' + index" class="radar-chart" style="width: 100%;height: 280px;"></div>
          </div>
        </el-col>
        <el-divider/>
        <el-col :span="24" v-for="(c, i) in item.scores" :key="i" class="candidate-card-footer">
          <el-row class="candidate-card-footer-title" justify="space-between">
            <el-col class="title" :span="12">{{ i + 1 }}、{{ c.category }}</el-col>
            <el-col class="score" :span="12">匹配得分：{{ c.score }}分</el-col>
          </el-row>
          <el-row class="candidate-card-footer-description">{{ c.comment }}</el-row>
        </el-col>

      </el-row>
    </el-card>
  </StepLoading>
</template>

<style scoped lang="scss">
.card-title {
  font-weight: 500;
  font-size: 16px;
  color: #191919;
  line-height: 20px;
  margin-bottom: 17px;
}
.mb-8 {
  margin-bottom: 8px !important;
}
.card-description {
  width: 100%;
  font-weight: 400;
  font-size: 14px;
  color: #8C8C8C;
  line-height: 21px;
  margin-bottom: 14px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.candidate-card {
  &:nth-child(3n - 2) {
    background: linear-gradient( 217deg, rgba(48,103,239,0.1) 0%, rgba(48,103,239,0.03) 100%);
    border-radius: 12px 12px 12px 12px;
    .name, .candidate-card-left-reason-title, .score {
      color: #3767DD !important;
    }
    .candidate-card-left-reason {
      background: #EAF1FF;
      border: 1px solid #D7E0FA;
    }
  }
  &:nth-child(3n - 1) {
    background: linear-gradient( 217deg, rgba(48,239,201,0.1) 0%, rgba(48,239,182,0.03) 100%);
    border: 1px solid rgba(50,172,151,0.1);
    .name, .candidate-card-left-reason-title, .score {
      color: #32AC97 !important;
    }
    .candidate-card-left-reason {
      background: rgba(50,172,151,0.05);
      border: 1px solid rgba(50,172,151,0.13);
    }
  }
  &:nth-child(3n) {
    background: linear-gradient( 217deg, rgba(255,204,19,0.1) 0%, rgba(239,223,48,0.03) 100%);
    border: 1px solid rgba(234,152,21,0.1);
    .name, .candidate-card-left-reason-title, .score {
      color: #EA9815 !important;
    }
    .candidate-card-left-reason {
      background: rgba(234,152,21,0.05);
      border: 1px solid rgba(201,135,29,0.16);
    }
  }
  //border: 1px solid rgba(48,103,239,0.1);
  padding: 30px 40px;
  margin-bottom: 20px;
  &-left {
    &-name {
      position: relative;
      .line {
        width: 2px;
        height: 50px;
        background-color: rgba(0,0,0,0.2);
        position: absolute;
        left: 35%;
        transform: rotate(25deg);
      }
    }
    &-reason {
      width: 100%;
      padding: 16px;
      margin-top: 24px;
      background: #EAF1FF;
      border-radius: 8px 8px 8px 8px;
      border: 1px solid #D7E0FA;
      font-weight: 400;
      font-size: 14px;
      color: rgba(0,0,0,0.8);
      line-height: 25px;
      &-title {
        font-weight: 500;
        font-size: 16px;
        color: #3767DD;
        line-height: 24px;
        img {
          width: 16px;
          height: 16px;
          margin-right: 5px;
          position: relative;
          top: 2px;
        }
      }
      &-content {
        font-weight: 400;
        font-size: 14px;
        color: rgba(0,0,0,0.8);
        line-height: 25px;
        overflow: hidden;
        text-overflow: ellipsis;
        -webkit-line-clamp: 4;
        display: -webkit-box;
        -webkit-box-orient: vertical;
      }
    }
  }
  :deep(.el-divider) {
    margin-top: 10px;
    margin-bottom: 10px;
  }
  &-footer {
    &-title {
      margin-top: 24px;
      .title {
        font-weight: 500;
        font-size: 16px;
        color: #191919;
        line-height: 20px;
      }
      .score {
        text-align: right;
        font-weight: 500;
        font-size: 16px;
        line-height: 20px;
      }
    }
    &-description {
      margin-top: 8px;
      font-weight: 400;
      font-size: 14px;
      color: #515151;
      line-height: 25px;
    }
  }
}
</style>
